import { useState, useEffect } from 'react';
import { LLMConfigComponentProps } from './types';

export const LLMConfigComponent = ({ config, onChange }: LLMConfigComponentProps) => {
  const [localConfig, setLocalConfig] = useState(config);
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [touched, setTouched] = useState<Record<string, boolean>>({});
  const [showapi_key, setShowapi_key] = useState(false);

  useEffect(() => {
    setLocalConfig(config);
    const formErrors = validateForm(config);
    setErrors(formErrors);
  }, [config]);

  // 验证单个字段
  const validateField = (name: string, value: any): string => {
    switch (name) {
      case 'base_url':
        if (!value.trim()) return 'API基本URL不能为空';
        try {
          new URL(value);
          return '';
        } catch (e) {
          return '请输入有效的URL地址';
        }
      
      case 'api_key':
        if (!value.trim()) return 'API密钥不能为空';
        if (value.trim().length < 8) return 'API密钥长度不足';
        return '';
      
      case 'temperature':
        if (value < 0 || value > 10) return '温度值必须在0到10之间';
        return '';
      
      case 'max_tokens':
        if (isNaN(value) || value <= 0) return '令牌数必须为正数';
        if (value > 8192) return '令牌数超过最大限制';
        return '';
        
      case 'model':
        if (!value) return '模型名称不能为空';
        return '';
        
      default:
        return '';
    }
  };

  // 验证整个表单
  const validateForm = (data: typeof localConfig): Record<string, string> => {
    const newErrors: Record<string, string> = {};
    
    // 验证每个字段
    Object.entries(data).forEach(([key, value]) => {
      const error = validateField(key, value);
      if (error) {
        newErrors[key] = error;
      }
    });
    
    return newErrors;
  };

  // 处理触摸状态（用户是否与字段交互过）
  const handleBlur = (e: React.FocusEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name } = e.target;
    setTouched(prev => ({ ...prev, [name]: true }));
    
    // 验证单个字段
    const error = validateField(name, localConfig[name as keyof typeof localConfig]);
    setErrors(prev => ({ ...prev, [name]: error }));
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    let parsedValue: string | number = value;
    
    if (name === 'temperature' || name === 'max_tokens') {
      parsedValue = parseFloat(value);
    }

    const updatedConfig = {
      ...localConfig,
      [name]: parsedValue
    };
    
    setLocalConfig(updatedConfig);
    
    // 如果字段已经被触摸过，验证它
    if (touched[name]) {
      const error = validateField(name, parsedValue);
      setErrors(prev => ({ ...prev, [name]: error }));
    }
    
    onChange(updatedConfig);
  };

  // 切换API密钥显示
  const toggleapi_keyVisibility = () => {
    setShowapi_key(!showapi_key);
  };

  return (
    <div className="space-y-6">
      <h2 className="text-lg font-medium">LLM 配置</h2>
      <p className="text-sm text-gray-500">配置自动化任务中使用的语言模型的设置。</p>
      
      <div className="space-y-4">
        <h3 className="text-md font-medium">连接设置</h3>
        
        <div>
          <label htmlFor="base_url" className="block text-sm font-medium text-gray-700 mb-1">
            API基本URL
          </label>
          <input
            type="text"
            id="base_url"
            name="base_url"
            value={localConfig.base_url}
            onChange={handleInputChange}
            onBlur={handleBlur}
            className={`w-full p-2 border ${errors.base_url ? 'border-red-500' : 'border-gray-300'} rounded-md`}
            placeholder="https://api.openai.com/v1"
          />
          {errors.base_url && touched.base_url && (
            <p className="mt-1 text-xs text-red-500">{errors.base_url}</p>
          )}
          <p className="mt-1 text-xs text-gray-500">LLM API 的基本 URL。</p>
        </div>
        
        <div>
          <label htmlFor="api_key" className="block text-sm font-medium text-gray-700 mb-1">
            API 密钥
          </label>
          <div className="relative">
            <input
              type={showapi_key ? "text" : "password"}
              id="api_key"
              name="api_key"
              value={localConfig.api_key}
              onChange={handleInputChange}
              onBlur={handleBlur}
              className={`w-full p-2 border ${errors.api_key ? 'border-red-500' : 'border-gray-300'} rounded-md`}
              placeholder="输入您的 API 密钥"
            />
            <button
              type="button"
              onClick={toggleapi_keyVisibility}
              className="absolute inset-y-0 right-0 pr-3 flex items-center text-sm leading-5 text-gray-500 hover:text-gray-700"
            >
              {showapi_key ? 
                <span>隐藏</span> : 
                <span>显示</span>
              }
            </button>
          </div>
          {errors.api_key && touched.api_key && (
            <p className="mt-1 text-xs text-red-500">{errors.api_key}</p>
          )}
          <p className="mt-1 text-xs text-gray-500">用于身份验证的 API 密钥。</p>
        </div>
        
        <div className="space-y-4 mt-6">
          <h3 className="text-md font-medium">模型设置</h3>
          
          <div>
            <label htmlFor="model" className="block text-sm font-medium text-gray-700 mb-1">
              模型名称
            </label>
            <input
              type="text"
              id="model"
              name="model"
              value={localConfig.model}
              onChange={handleInputChange}
              onBlur={handleBlur}
              className={`w-full p-2 border ${errors.model ? 'border-red-500' : 'border-gray-300'} rounded-md`}
              placeholder="例如：gpt-4o, gpt-3.5-turbo"
            />
            {errors.model && touched.model && (
              <p className="mt-1 text-xs text-red-500">{errors.model}</p>
            )}
            <p className="mt-1 text-xs text-gray-500">输入要使用的LLM模型名称。</p>
          </div>
          
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label htmlFor="temperature" className="block text-sm font-medium text-gray-700 mb-1">
                采样温度
              </label>
              <input
                type="number"
                id="temperature"
                name="temperature"
                min="0"
                max="10"
                step="0.1"
                value={localConfig.temperature}
                onChange={handleInputChange}
                onBlur={handleBlur}
                className={`w-full p-2 border ${errors.temperature ? 'border-red-500' : 'border-gray-300'} rounded-md`}
              />
              {errors.temperature && touched.temperature && (
                <p className="mt-1 text-xs text-red-500">{errors.temperature}</p>
              )}
              <p className="mt-1 text-xs text-gray-500">控制随机性 (0-10) 。</p>
            </div>
            
            <div>
              <label htmlFor="max_tokens" className="block text-sm font-medium text-gray-700 mb-1">
                最大令牌数
              </label>
              <input
                type="number"
                id="max_tokens"
                name="max_tokens"
                min="1"
                max="8192"
                value={localConfig.max_tokens}
                onChange={handleInputChange}
                onBlur={handleBlur}
                className={`w-full p-2 border ${errors.max_tokens ? 'border-red-500' : 'border-gray-300'} rounded-md`}
              />
              {errors.max_tokens && touched.max_tokens && (
                <p className="mt-1 text-xs text-red-500">{errors.max_tokens}</p>
              )}
              <p className="mt-1 text-xs text-gray-500">最大输出长度(0-8192)。</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default LLMConfigComponent;